"""
AI Agent Pro - 简化演示脚本
不依赖外部库的基础功能展示
"""

import asyncio
import json
import time
import uuid
from typing import Any, Dict, List, Optional
from dataclasses import dataclass
from enum import Enum


# 简化的智能体状态枚举
class AgentState(str, Enum):
    IDLE = "idle"
    THINKING = "thinking"
    ACTING = "acting"
    ERROR = "error"


# 简化的消息模型
@dataclass
class Message:
    id: str
    role: str
    content: str
    timestamp: float
    
    def __post_init__(self):
        if not self.id:
            self.id = str(uuid.uuid4())
        if not self.timestamp:
            self.timestamp = time.time()


# 简化的工具结果
@dataclass
class ToolResult:
    success: bool
    data: Any = None
    error: Optional[str] = None
    execution_time: float = 0.0


# 简化的智能体配置
@dataclass
class AgentConfig:
    name: str
    description: str = ""
    model: str = "mock-gpt-4"
    temperature: float = 0.7
    max_tokens: int = 2000
    system_prompt: str = ""
    tools: List[str] = None
    thinking_enabled: bool = True
    
    def __post_init__(self):
        if self.tools is None:
            self.tools = []


# 模拟AI模型
class MockModel:
    def __init__(self, model_name: str = "mock-gpt-4"):
        self.model_name = model_name
    
    async def generate(self, prompt: str, system_prompt: str = None, **kwargs) -> str:
        """模拟生成响应"""
        await asyncio.sleep(0.5)  # 模拟API调用延迟
        
        # 简单的模拟逻辑
        if "你好" in prompt or "hello" in prompt.lower():
            return "你好！我是AI智能体助手，很高兴为您服务！我可以帮您处理各种任务。"
        elif "编程" in prompt or "代码" in prompt or "code" in prompt.lower():
            return """我可以帮您编写和调试代码！以下是一个简单的Python函数示例：

```python
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 使用示例
for i in range(10):
    print(f"F({i}) = {fibonacci(i)}")
```

需要什么具体的编程帮助吗？我可以帮您：
- 编写函数和算法
- 调试代码问题  
- 优化性能
- 解释代码逻辑"""
        elif "计算" in prompt or "math" in prompt.lower():
            return "我可以帮您进行数学计算和分析。例如：\n- 基础运算：2 + 3 × 4 = 14\n- 几何计算：圆形面积 = π × r²\n- 统计分析：均值、方差、标准差等\n\n请告诉我具体需要计算什么？"
        elif "搜索" in prompt or "search" in prompt.lower():
            return f"我可以帮您搜索关于 '{prompt}' 的信息。搜索结果包括：\n\n1. 📄 技术文档和教程\n2. 🔬 最新研究成果\n3. 💼 实际应用案例\n4. 🎓 学习资源推荐\n\n需要我深入搜索哪个方面的内容？"
        else:
            return f"我理解您的问题：「{prompt[:50]}{'...' if len(prompt) > 50 else ''}」\n\n让我为您详细分析：\n- 这是一个很有趣的问题\n- 涉及到多个方面的考虑\n- 我可以从不同角度为您解答\n\n您希望我重点关注哪个方面？"


# 简化的智能体核心类
class SimpleAgent:
    def __init__(self, config: AgentConfig):
        self.id = str(uuid.uuid4())
        self.config = config
        self.state = AgentState.IDLE
        self.model = MockModel(config.model)
        self.conversation_history: List[Message] = []
        self.stats = {
            "total_messages": 0,
            "average_response_time": 0.0,
            "successful_responses": 0
        }
    
    async def chat(self, user_message: str, user_id: Optional[str] = None) -> str:
        """与智能体对话"""
        start_time = time.time()
        
        try:
            # 更新状态
            self.state = AgentState.THINKING
            
            # 添加用户消息
            user_msg = Message(
                id=str(uuid.uuid4()),
                role="user",
                content=user_message,
                timestamp=time.time()
            )
            self.conversation_history.append(user_msg)
            
            # 模拟思考过程
            if self.config.thinking_enabled:
                print(f"🤔 {self.config.name} 正在思考...")
                await asyncio.sleep(0.3)
            
            # 构建提示词
            prompt = self._build_prompt(user_message)
            
            # 生成回复
            response = await self.model.generate(prompt, self.config.system_prompt)
            
            # 添加助手消息
            assistant_msg = Message(
                id=str(uuid.uuid4()),
                role="assistant", 
                content=response,
                timestamp=time.time()
            )
            self.conversation_history.append(assistant_msg)
            
            # 更新统计
            end_time = time.time()
            duration = end_time - start_time
            self._update_stats(duration)
            
            self.state = AgentState.IDLE
            return response
            
        except Exception as e:
            self.state = AgentState.ERROR
            return f"抱歉，处理请求时发生错误: {str(e)}"
    
    def _build_prompt(self, user_message: str) -> str:
        """构建提示词"""
        prompt_parts = []
        
        if self.config.system_prompt:
            prompt_parts.append(f"系统: {self.config.system_prompt}")
        
        # 添加最近的对话历史
        if self.conversation_history:
            recent_history = self.conversation_history[-6:]  # 最近3轮对话
            for msg in recent_history:
                prompt_parts.append(f"{msg.role}: {msg.content}")
        
        prompt_parts.append(f"用户: {user_message}")
        prompt_parts.append("助手:")
        
        return "\n".join(prompt_parts)
    
    def _update_stats(self, response_time: float):
        """更新统计信息"""
        self.stats["total_messages"] += 1
        self.stats["successful_responses"] += 1
        
        # 计算平均响应时间
        total_time = self.stats["average_response_time"] * (self.stats["total_messages"] - 1)
        self.stats["average_response_time"] = (total_time + response_time) / self.stats["total_messages"]
    
    def get_status(self) -> Dict[str, Any]:
        """获取智能体状态"""
        return {
            "id": self.id,
            "name": self.config.name,
            "state": self.state.value,
            "model": self.config.model,
            "conversation_length": len(self.conversation_history),
            "stats": self.stats.copy()
        }
    
    def reset_conversation(self):
        """重置对话历史"""
        self.conversation_history.clear()
        print(f"🔄 {self.config.name} 的对话历史已重置")


# 智能体工厂
class SimpleAgentFactory:
    @staticmethod
    def create_agent(config: AgentConfig) -> SimpleAgent:
        return SimpleAgent(config)
    
    @staticmethod
    def create_from_template(template_name: str, name: str, **kwargs) -> SimpleAgent:
        templates = {
            "coding_assistant": AgentConfig(
                name=name,
                description="专业编程助手",
                model="mock-gpt-4-code",
                temperature=0.1,
                system_prompt="你是一个专业的编程助手，能够帮助用户编写、调试和优化代码。你精通多种编程语言，能够提供清晰的解释和实用的建议。",
                tools=["code_executor", "file_manager"],
                thinking_enabled=True
            ),
            "research_assistant": AgentConfig(
                name=name,
                description="研究助手",
                model="mock-claude-3",
                temperature=0.3,
                system_prompt="你是一个专业的研究助手，能够帮助用户收集信息、分析数据、总结要点。你擅长逻辑思维和批判性分析。",
                tools=["web_search", "document_analyzer"],
                thinking_enabled=True
            ),
            "creative_writer": AgentConfig(
                name=name,
                description="创意写作助手", 
                model="mock-gpt-4-creative",
                temperature=0.8,
                system_prompt="你是一个富有创意的写作助手，能够帮助用户创作故事、文章和各种文本内容。你富有想象力，文笔优美。",
                tools=["text_analyzer"],
                thinking_enabled=True
            )
        }
        
        if template_name not in templates:
            raise ValueError(f"未知模板: {template_name}")
        
        config = templates[template_name]
        
        # 应用自定义参数
        for key, value in kwargs.items():
            if hasattr(config, key):
                setattr(config, key, value)
        
        return SimpleAgentFactory.create_agent(config)


def print_banner():
    """打印启动横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════╗
║                    🤖 AI Agent Pro 🤖                        ║
║                                                              ║
║              专业智能体开发平台演示系统                        ║
║                   (简化版本 - 无外部依赖)                     ║
╚══════════════════════════════════════════════════════════════╝
"""
    print(banner)


def print_feature_overview():
    """打印功能概览"""
    print("\n🚀 核心功能演示")
    print("=" * 50)
    
    features = {
        "🧠 智能体引擎": [
            "多模型支持架构",
            "可配置的推理参数", 
            "思考过程展示",
            "状态管理和监控"
        ],
        "💬 对话交互": [
            "多轮对话支持",
            "上下文理解",
            "个性化回复",
            "实时状态反馈"
        ],
        "📊 统计分析": [
            "响应时间统计",
            "对话轮次计数",
            "成功率监控",
            "性能指标展示"
        ],
        "🎯 模板系统": [
            "预定义智能体模板",
            "快速创建实例",
            "参数自定义",
            "用途专业化"
        ]
    }
    
    for category, items in features.items():
        print(f"\n{category}:")
        for item in items:
            print(f"  ✓ {item}")


async def demo_basic_agent():
    """演示基础智能体功能"""
    print("\n🤖 基础智能体演示")
    print("=" * 50)
    
    # 创建智能体配置
    config = AgentConfig(
        name="演示助手",
        description="一个用于演示的AI助手",
        model="mock-gpt-4", 
        temperature=0.7,
        system_prompt="你是一个友好、专业的AI助手，能够帮助用户解决各种问题。",
        thinking_enabled=True
    )
    
    # 创建智能体实例
    agent = SimpleAgentFactory.create_agent(config)
    
    print(f"✅ 智能体创建成功: {agent.config.name}")
    print(f"🆔 智能体ID: {agent.id[:8]}...")
    print(f"🧠 使用模型: {agent.config.model}")
    print()
    
    # 测试对话
    test_messages = [
        "你好！",
        "你能帮我写一个Python排序算法吗？", 
        "计算圆形面积的公式是什么？",
        "搜索一下机器学习的最新发展"
    ]
    
    for i, message in enumerate(test_messages, 1):
        print(f"👤 用户 {i}: {message}")
        
        try:
            # 获取回复
            response = await agent.chat(message, user_id="demo_user")
            print(f"🤖 {agent.config.name}: {response}")
            
        except Exception as e:
            print(f"❌ 错误: {str(e)}")
        
        print("-" * 60)
        
        # 添加延迟让演示更自然
        await asyncio.sleep(1)
    
    # 显示智能体状态
    status = agent.get_status()
    print("\n📊 智能体状态:")
    for key, value in status.items():
        print(f"  {key}: {value}")


async def demo_template_agents():
    """演示模板智能体"""
    print("\n🏭 模板智能体演示")
    print("=" * 50)
    
    # 创建不同类型的智能体
    agents = {}
    
    try:
        # 编程助手
        agents["coder"] = SimpleAgentFactory.create_from_template(
            template_name="coding_assistant",
            name="代码大师",
            temperature=0.1
        )
        print(f"✅ 编程助手创建成功: {agents['coder'].config.name}")
        
        # 研究助手
        agents["researcher"] = SimpleAgentFactory.create_from_template(
            template_name="research_assistant", 
            name="研究专家",
            temperature=0.3
        )
        print(f"✅ 研究助手创建成功: {agents['researcher'].config.name}")
        
        # 创意写作助手
        agents["writer"] = SimpleAgentFactory.create_from_template(
            template_name="creative_writer",
            name="文学创作家",
            temperature=0.8
        )
        print(f"✅ 创意助手创建成功: {agents['writer'].config.name}")
        
        print()
        
        # 测试每个智能体
        test_scenarios = [
            ("coder", "帮我实现一个二分查找算法"),
            ("researcher", "分析一下人工智能的发展趋势"),
            ("writer", "写一个关于未来科技的短故事开头")
        ]
        
        for agent_type, message in test_scenarios:
            agent = agents[agent_type]
            print(f"👤 测试 {agent.config.name}: {message}")
            response = await agent.chat(message)
            print(f"🤖 {agent.config.name}: {response[:200]}{'...' if len(response) > 200 else ''}")
            print("-" * 60)
            await asyncio.sleep(1)
        
    except Exception as e:
        print(f"❌ 模板智能体创建失败: {str(e)}")


async def demo_conversation_flow():
    """演示对话流程"""
    print("\n💬 对话流程演示")
    print("=" * 50)
    
    # 创建一个智能体进行多轮对话
    config = AgentConfig(
        name="对话专家",
        model="mock-gpt-4-chat",
        system_prompt="你是一个专业的对话助手，善于记住对话上下文，能够进行连贯的多轮对话。",
        thinking_enabled=True
    )
    
    agent = SimpleAgentFactory.create_agent(config)
    
    # 模拟连续对话
    conversation_flow = [
        "我想学习Python编程",
        "从哪里开始比较好？",
        "那数据结构重要吗？",
        "能推荐一些练习项目吗？"
    ]
    
    print(f"开始与 {agent.config.name} 进行多轮对话...\n")
    
    for i, message in enumerate(conversation_flow, 1):
        print(f"🗣️  第 {i} 轮对话")
        print(f"👤 用户: {message}")
        
        response = await agent.chat(message)
        print(f"🤖 {agent.config.name}: {response}")
        print(f"📈 对话历史长度: {len(agent.conversation_history)} 条消息")
        print("-" * 60)
        await asyncio.sleep(1.5)
    
    # 显示对话统计
    print(f"\n📊 对话统计:")
    stats = agent.get_status()["stats"]
    for key, value in stats.items():
        if isinstance(value, float):
            print(f"  {key}: {value:.2f}")
        else:
            print(f"  {key}: {value}")


async def interactive_demo():
    """交互式演示"""
    print("\n🎮 交互式演示")
    print("=" * 50)
    print("现在您可以与智能体进行实时对话！")
    print("输入 'quit' 退出，输入 'reset' 重置对话，输入 'status' 查看状态")
    print()
    
    # 创建默认智能体
    config = AgentConfig(
        name="交互助手",
        model="mock-gpt-4-interactive",
        system_prompt="你是一个友好的交互助手，能够与用户进行自然的对话。保持回复简洁而有用。",
        thinking_enabled=False  # 交互模式下关闭思考显示
    )
    
    agent = SimpleAgentFactory.create_agent(config)
    print(f"🤖 {agent.config.name} 已准备就绪！")
    
    while True:
        try:
            # 获取用户输入
            user_input = input("\n👤 您: ").strip()
            
            if not user_input:
                continue
            
            if user_input.lower() == 'quit':
                print("👋 再见！感谢使用 AI Agent Pro!")
                break
            elif user_input.lower() == 'reset':
                agent.reset_conversation()
                continue
            elif user_input.lower() == 'status':
                status = agent.get_status()
                print(f"\n📊 智能体状态:")
                for key, value in status.items():
                    if key != "stats":
                        print(f"  {key}: {value}")
                print(f"  统计信息:")
                for k, v in status["stats"].items():
                    if isinstance(v, float):
                        print(f"    {k}: {v:.2f}")
                    else:
                        print(f"    {k}: {v}")
                continue
            
            # 获取智能体回复
            response = await agent.chat(user_input)
            print(f"🤖 {agent.config.name}: {response}")
            
        except KeyboardInterrupt:
            print("\n👋 再见！")
            break
        except Exception as e:
            print(f"❌ 发生错误: {str(e)}")


async def main():
    """主演示函数"""
    print_banner()
    print_feature_overview()
    
    try:
        # 基础智能体演示
        await demo_basic_agent()
        
        # 模板智能体演示  
        await demo_template_agents()
        
        # 对话流程演示
        await demo_conversation_flow()
        
        # 询问是否进入交互模式
        print("\n" + "="*60)
        response = input("是否进入交互式演示模式？(y/n): ").strip().lower()
        
        if response in ['y', 'yes', '是']:
            await interactive_demo()
        
        print("\n🎉 演示完成！")
        print("\n📝 后续步骤:")
        print("1. 安装完整依赖: pip install -r backend/requirements.txt")
        print("2. 配置真实的AI模型API密钥") 
        print("3. 设置数据库和Redis")
        print("4. 启动完整的FastAPI服务")
        print("5. 开发自定义工具和功能")
        print("\n📚 查看完整文档: README.md")
        
    except Exception as e:
        print(f"\n❌ 演示过程中发生错误: {str(e)}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n👋 演示被用户中断，再见！")
    except Exception as e:
        print(f"\n❌ 启动失败: {str(e)}")